#include "animation2d.h"


namespace teflon
{

    AnimatedSprite::AnimatedSprite(glm::vec2& pos, glm::vec2& size, const std::string& image_path,
        uint32_t xcount, uint32_t ycount, float fps)
    {
        this->pos = pos;
        this->size = size;
        this->texture = Texture2D::fromImageFile(image_path);
        this->size_x = xcount;
        this->size_y = ycount;
        this->fps = fps;
        this->time_elapsed = 0.0f;
    }

    void AnimatedSprite::Update(float delta_t)
    {
        time_elapsed += delta_t;
        uint32_t index = static_cast<uint32_t>(time_elapsed * fps);
        this->uv = GetUV(index);
    }

    glm::vec4 AnimatedSprite::GetUV(uint32_t index)
    {
        index = index % (size_x * size_y);
        uint32_t yoff = index / size_x;
        uint32_t xoff = index - yoff * size_x;
        float dx = 1.0f / size_x;
        float dy = 1.0f / size_y;
        uv.r = dx * xoff;
        uv.g = dy * yoff;
        uv.b = dx * xoff + dx;
        uv.a = dy * yoff + dy;
        return uv;
    }
}
